// const URL = "http://127.0.0.1:3000/mg/video";
// let URL = "http://42.194.197.253/mg/video";

let CREATE_URL = "https://jsz315.xyz/ns/video/create";
let DOWNLOAD_URL = "https://jsz315.xyz/ns/video/download";


let exampleElement = document.body;
let contextMenu;

function tapDiv(n) {
    console.log(n);
}

// var chromeRuntimePort = chrome.runtime.connect();

// 右键菜单事件
exampleElement.addEventListener("contextmenu", function (event) {
    if (contextMenu) {
        clear();
    }
    if (!checkHas(event.target)) {
        return;
    }

    event.preventDefault(); // 阻止默认右键菜单
    event.stopImmediatePropagation();
    event.stopPropagation();
    // console.log(event, "dddd");

    let webs = JSON.parse(localStorage.getItem("webs"))

    hideOther();

    // 创建菜单
    contextMenu = document.createElement("div");
    contextMenu.classList.add('menu-items');
    // contextMenu.innerHTML = `
    // <div class="menu-item" id='add'>添加记录</div>
    // <div class="menu-item" id='m2'>下载视频</div>
    // `;
    let ary = [];
    ary.push(`<div class="menu-item" id='add'>添加记录</div>`);
    webs.forEach(i => {
        ary.push(`<div class="menu-item" id='${i.name}'>${i.name}</div>`);
    });

    contextMenu.innerHTML = ary.join('');

    // Object.assign(contextMenu.style, menuStyles);
    positionContextMenu(event);

    // 添加菜单到页面
    document.body.appendChild(contextMenu);

    // 获取菜单项
    // const menuItem = contextMenu.querySelector('.menu-item');

    // 点击菜单项事件
    contextMenu.addEventListener("click", clickMenu);
    // 点击其他地方移除菜单
    document.addEventListener("click", clickOutside);

    function clickMenu(e) {
        openLink(event.target, e.target);

        if (contextMenu) {
            // 移除菜单
            clear();
        }
    }

    function clear() {
        // return;
        if (contextMenu) {
            if (document.body.contains(contextMenu)) {
                document.body.removeChild(contextMenu);
            }
            document.removeEventListener("click", clickOutside);
            contextMenu.removeEventListener("click", clickMenu);
            contextMenu = null;
        }
    }

    function clickOutside(e) {
        if (contextMenu && !contextMenu.contains(e.target)) {
            clear();
        }
    }

    return false;
});

function findParent(element) {
    while (element) {
        if (element.tagName.toLocaleLowerCase() === "article") {
            return element;
        }
        element = element.parentElement;
    }
    return null;
}


function findParent2(element) {
    while (element) {
        if (element.classList.contains("menu-item")) {
            return element;
        }
        element = element.parentElement;
    }
    return null;
}

function checkHas(element) {
    console.log(element.clientWidth, element.clientHeight);
    if (element.clientWidth < 100 || element.clientHeight < 80) {
        return false;
    }
    let item = findParent(element);
    if (!item) {
        return false;
    }
    let video = item.querySelector("video");
    if (!video) {
        return false;
    }
    return true;
}

function hideOther() {
    let dom = document.querySelector('[role="menuitem"]');
    if (dom) {
        dom.parentNode.style.visibility = "hidden";
    }
}

var port = chrome.runtime.connect({ name: "knockknock" });
// port.postMessage({ac: "Knock knock"});
port.onMessage.addListener(function (msg) {
    console.log(msg, "---")
});

function openLink(dom, target) {
    let element = findParent(dom);
    if (!element) return false;

    console.log(target.id);
    // return;

    let src = getSrc(element);
    if (!src) {
        msg("查找链接失败", false);
        return false;
    }

    target = findParent2(target)

    if (target.id == "add") {
        let t = element.querySelector("video");
        if (!t) {
            msg("查找视频失败", false, 3200);
            return false;
        }

        let poster = t.getAttribute("poster");
        console.log("poster", poster);

        let duration = t.duration;
        console.log("duration", duration);

        let title = getTitle(element);

        console.log("title", title);

        let date = element.querySelector("time").getAttribute("datetime");
        console.log("date", date);

        // (async () => {
        //     const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
        //     const response = await chrome.tabs.sendMessage(tab.id, { action: "img", poster });
        //     // do something with response here, not outside the function
        //     console.log("后台响应数据", response);
        // })();

        // port.postMessage({ action: "img", poster });


        post({ src, poster, title, date, duration });


    }
    else {
        let twitterUrl = `https:/${target.id}/?url=` + encodeURIComponent(src);
        // chrome.tabs.create({ url: twitterUrl });
        window.open(twitterUrl)
        console.log("发送链接到页面成功")
        msg("发送到页面成功", true)
    }
}

function getSrc(element) {
    let ary = element.querySelectorAll("a");
    let item = [...ary].find(i => i.href.match(/\/\d+$/));
    if (item) {
        return item.href;
    }
    return null;
}

function getTitle(element) {
    // let dom = element.querySelector(".css-1rynq56.r-dnmrzs.r-bcqeeo.r-rjixqe.r-bnwqim");
    let dom = element.querySelector('[dir="auto"]')
    if (dom) {
        return dom.innerText;
    }
    return "";
}

function post(param) {
    // fetch("https://jsz315.xyz/ns").then(response => response.json())
    // .then(res => {
    //     console.log(res.data);
    //     msg(res.data);
    // })
    // .catch(error => {
    //     msg("保存错误", false, 900);
    // });

    fetch(CREATE_URL, {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(param)
    })
        .then(response => response.json())
        .then(res => {
            console.log("res", res)
            if (res.insertedId) {
                msg("保存成功", true, 900);
            } else {
                msg("保存失败", false, 900);
            }
        })
        .catch(error => {
            msg("保存错误", false, 900);
        });
}

async function msg(str, suc = true, delay = 300) {
    console.log(str);
    await sleep(delay);

    const div = document.createElement("div");
    div.classList.add("jsz-tips");
    div.classList.add(suc ? "suc" : "fail");
    div.innerHTML = str;
    document.body.appendChild(div);
    await sleep(3000);
    document.body.removeChild(div);
}

function sleep(n) {
    return new Promise(resolve => setTimeout(resolve, n));
}

function positionContextMenu(event) {
    contextMenu.style.top = `${event.clientY}px`;
    contextMenu.style.left = `${event.clientX}px`;
}
